package com.wanwu.channel.server.controller;

import com.wanwu.channel.common.enums.ExceptionEnum;
import com.wanwu.channel.common.exception.SystemException;
import com.wanwu.channel.common.util.LogUtil;
import com.wanwu.channel.common.util.XmlUtil;
import com.wanwu.channel.remote.wxpay.config.WeixinGlobalConfig;
import com.wanwu.channel.remote.wxpay.util.AESUtil;
import com.wanwu.channel.remote.wxpay.util.WXPayUtil;
import com.wanwu.channel.remote.wxpay.util.WechatSignUtil;
import com.wanwu.channel.server.model.NotifyResponse;
import com.wanwu.channel.server.process.WexinNotifyProcess;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;

/**
 * @ClassName WechatNotifyController
 * @Description 微信支付结果回调处理
 * @Author husheng
 * @Date 2020-01-06 17:32
 */
@RestController
@EnableConfigurationProperties(WeixinGlobalConfig.class)
@RequestMapping("/wechat")
public class WechatNotifyController {

    private static Logger logger = LoggerFactory.getLogger(WechatNotifyController.class);

    @Autowired
    private WeixinGlobalConfig weixinGlobalConfig;

    @Autowired
    private WexinNotifyProcess wexinNotifyProcess;

    /**
     * 微信支付回调处理
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/pay/notify/{bizCode}", method = RequestMethod.POST)
    public String appPayNotify(HttpServletRequest request,@PathVariable String bizCode) {
        NotifyResponse response = new NotifyResponse();
        try {
            String wechatNotifyStr = getRequestString(request);
            LogUtil.info(logger, "接收到【微信支付】结果回调请求，{0}", wechatNotifyStr);
            //验证签名
            boolean verifyResult = WechatSignUtil.verifySign(wechatNotifyStr, weixinGlobalConfig.getApiKey());
            if (!verifyResult) {
                throw new SystemException(ExceptionEnum.E10009);
            }
            response = wexinNotifyProcess.weixinPayNotify(wechatNotifyStr,bizCode);
        } catch (Exception e) {
            LogUtil.error(logger, e, "处理微信支付结果回调失败");
            response.setReturnCode("FAIL");
            if (e instanceof IOException) {
                response.setReturnMsg("通知报文解析失败");
            } else if (e instanceof SystemException) {
                SystemException ex = (SystemException) e;
                response.setReturnMsg(ex.getMsg());
            } else {
                response.setReturnMsg("系统未知异常");
            }
        }
        String responseXml = XmlUtil.toXml(response);
        LogUtil.info(logger, "处理微信支付结果回调返回报文，{0}", responseXml);
        return responseXml;
    }


    /**
     * 返回微信处理结果
     *
     * @param response
     * @return
     */
    private String returnWechat(NotifyResponse response) {
        String responseXml = XmlUtil.toXml(response);
        LogUtil.info(logger, "处理微信支付结果回调返回报文，{0}", responseXml);
        return responseXml;
    }

    private String getRequestString(HttpServletRequest request) throws IOException {
        //读取微信回调报文
        ServletInputStream instream = request.getInputStream();
        StringBuffer sb = new StringBuffer();
        int len = -1;
        byte[] buffer = new byte[1024];
        while ((len = instream.read(buffer)) != -1) {
            sb.append(new String(buffer, 0, len));
        }
        instream.close();
        //获得xml报文
        String wechatNotifyStr = sb.toString();
        return wechatNotifyStr;
    }

}
